<?php

namespace app\admin\controller;

use app\common\model\ConfigPubModel;
use app\common\model\VideoModel;
use app\common\model\VideoReplayCategoryModel;

class VideoController extends BaseController
{
    public function index()
    {
        if ($this->request->isAjax()) {
            $model = VideoModel::field('*')->where('type','not in','5,7');
            if ($title = trim($this->get('title', ''))) {
                $model = $model->whereLike('title', $title . '%');
            }

            if (in_array($type = $this->get('type', ''), array_keys(VideoModel::TYPE))) {
                $model = $model->where('type', $type);
            }

            if (in_array($status = $this->get('status', ''), ['0', '1', '2'])) {
                $model = $model->where('status', $status);
            }

            if (($start_time = strtotime($this->get('start_time', ''))) && ($end_time = strtotime($this->get('end_time', '')))) {
                $model = $model->whereBetween('create_time', [$start_time, $end_time + 86399]);
            } elseif ($start_time) {
                $model = $model->whereBetween('create_time', [$start_time, time()]);
            }

            return json([
                'count' => $model->count('id'),
                'list' => $model->order('id', 'desc')
                    ->page($this->get('page', 1), $this->get('limit', 20))
                    ->select()
                    ->toArray(),
                'code' => 0,
            ]);
        }

        return $this->assign([
            'types' => VideoModel::TYPE,
            'url' => rtrim(ConfigPubModel::where('id', 1)->value('video_play_url '), '/')
        ])->fetch();
    }

    public function edit()
    {
        if (!ctype_digit($id = $this->get('id'))) {
            return static::bulidFail('ID错误');
        }

        if (!$model = VideoModel::where('id', $id)->find()) {
            return static::bulidFail('不存在的视频');
        }

        if ($this->request->isAjax()) {

            if (!$title = trim($this->post('title', ''))) {
                return static::bulidFail('视频标题不能为空');
            }

            if (mb_strlen($title) > 200) {
                return static::bulidFail('视频标题长度不能超过200个字符');
            }

            if (!in_array($type = $this->post('type', ''), array_keys(VideoModel::TYPE))) {
                return static::bulidFail('视频类型错误');
            }

            if (!$cover = trim($this->post('cover', ''))) {
                //return static::bulidFail('封面图片不能为空');
            }

            if (!ctype_digit($like_count = $this->post('like_count'))) {
                $like_count = 0;
            }

            if ($like_count < 0) {
                $like_count = 0;
            }

            if (!ctype_digit($play_count = $this->post('play_count'))) {
                $play_count = 0;
            }

            if ($like_count < 0) {
                $play_count = 0;
            }

            if (!in_array($status = $this->post('status'), ['1', '2'])) {
                $status = 0;
            }

            if (!in_array($is_hot = $this->post('is_hot'), ['0', '1'])) {
                $is_hot = 0;
            }
            if (!in_array($direction = $this->post('direction'), ['0', '1'])) {
                return static::bulidFail('横屏竖屏值错误');
            }

            $remark = trim($this->post('remark', ''));
            if (mb_strlen($remark) > 60) {
                return static::bulidFail('备注信息不能超过60个字符');
            }

            $model->type = $type;
            $model->play_count = $play_count;
            $model->like_count = $like_count;
            $model->title = $title;
            $model->status = $status;
            $model->is_hot = $is_hot;
            $model->remark = $remark;
            $model->operator = $this->admin_name;
            //$model->cover = $cover;
            $model->direction = $direction;

            if ($type != 5) {
                $model->replay_category = 0;
            }

            if (!$model->save()) {
                return static::bulidFail('视频编辑失败');
            }

            $this->addAdminLog('编辑了视频 视频ID:' . $model->id);

            return static::bulidSuccess(null, '视频编辑成功');
        }
        $conf = ConfigPubModel::field('video_upload_url,video_play_url')->where('id', 1)->find();
        return $this->assign([
            'types' => VideoModel::TYPE,
            'model' => $model,
            'video_upload_url' => rtrim($conf->video_upload_url, '/'),
            'video_play_url' => rtrim($conf->video_play_url, '/')
        ])->fetch();
    }

    public function status()
    {
        if (!ctype_digit($id = $this->post('id'))) {
            return static::bulidFail('ID错误');
        }

        if (!in_array($status = $this->post('status'), ['1', '2'])) {
            return static::bulidFail('状态错误');
        }

        if (!$model = VideoModel::where('id', $id)->find()) {
            return static::bulidFail('不存在的视频');
        }

        $title = $status == 1 ? '上架' : '下架';
        $model->status = $status;
        $model->operator = $this->admin_name;
        if (!$model->save()) {
            return static::bulidFail($title . '失败');
        }

        $this->addAdminLog($title . "了视频 视频ID:" . $id);

        return static::bulidSuccess(null, $title . '成功');
    }

    public function del()
    {
        if (!ctype_digit($id = $this->post('id'))) {
            return static::bulidFail('ID错误');
        }

        if (!$model = VideoModel::where('id', $id)->find()) {
            return static::bulidFail('不存在的视频');
        }

        if (!$model->delete()) {
            return static::bulidFail('删除失败');
        }

        $this->addAdminLog("删除了视频 视频ID:" . $id);

        return static::bulidSuccess(null, '删除成功');
    }

    public function upload()
    {
        $model = ConfigPubModel::field('video_upload_url,video_upload_key')->where('id', 1)->find();
        return $this->assign([
            'url' => rtrim($model->video_upload_url, '/'),
            'video_upload_key' => $model->video_upload_key,
        ])->fetch();
    }

    public function replay()
    {
        $replay_categorys = VideoReplayCategoryModel::where("parent_id=0")->column('name', 'id');
        $child_categorys = VideoReplayCategoryModel::where("parent_id!=0")->column('name', 'id');
        if ($this->request->isAjax()) {
            $model = VideoModel::field('*, replay_category as category')->where('type', 5);
            if ($title = trim($this->get('title', ''))) {
                $model = $model->whereLike('title', $title . '%');
            }
            $category = intval($this->get('category'));
            if ($category > 0) {
                $category_ids = VideoReplayCategoryModel::where("parent_id", $category)->column('id');
                if (count($category_ids) == 0) {
                    return json([
                        'count' => 0,
                        'list' => [],
                        'code' => 0,
                    ]);
                }
                $model = $model->where('replay_category', 'in', $category_ids);
            }
            $child_category = intval($this->get('child_category'));
            if ($child_category > 0) {
                $model = $model->where('replay_category', $child_category);
            }

            if (($start_time = strtotime($this->get('start_time', ''))) && ($end_time = strtotime($this->get('end_time', '')))) {
                $model = $model->whereBetween('create_time', [$start_time, $end_time + 86399]);
            } elseif ($start_time) {
                $model = $model->whereBetween('create_time', [$start_time, time()]);
            }

            $list = $model->order('id', 'desc')
                ->page($this->get('page', 1), $this->get('limit', 20))
                ->select()->each(function ($query) use (&$child_categorys) {
                    if (!empty($child_categorys[$query->replay_category])) {
                        $query->replay_category = $child_categorys[$query->replay_category];
                    } else {
                        $query->replay_category = '-';
                    }
                })
                ->toArray();
            foreach ($list as $key => $value) {
                if ($value['category'] > 0) {
                    $list_child = VideoReplayCategoryModel::where('id', $value['category'])->find();
                    if ($list_child['parent_id'] > 0) {
                        $parent = VideoReplayCategoryModel::where('id', $list_child['parent_id'])->find();
                        $list[$key]['parent_category'] = $parent['name'];
                    } else {
                        $list[$key]['parent_category'] = '-';
                    }
                }
            }

            return json([
                'count' => $model->count('id'),
                'list' => $list,
                'code' => 0,
            ]);
        }

        return $this->assign(['replay_categorys' => $replay_categorys, 'child_categorys' => $child_categorys])->fetch();
    }

    public function replay_edit()
    {
        if (!ctype_digit($id = $this->get('id'))) {
            return static::bulidFail('参数错误');
        }

        if (!$model = VideoModel::where('id', $id)->find()) {
            return static::bulidFail('视频不存在');
        }

        if ($this->request->isAjax()) {
            if (!$title = trim($this->post('title', ''))) {
                return static::bulidFail('回放标题不能为空');
            }

            if (mb_strlen($title) > 200) {
                return static::bulidFail('回放题长度不能超过200个字符');
            }

            if (!in_array($replay_category = $this->post('replay_category'), VideoReplayCategoryModel::column('id'))) {
                return static::bulidFail('回放类型错误');
            }

            if (!in_array($child_category = $this->post('child_category'), VideoReplayCategoryModel::column('id'))) {
                return static::bulidFail('回放二级类型错误');
            }

            if (!in_array($direction = $this->post('direction'), ['0', '1'])) {
                return static::bulidFail('横屏竖屏值错误');
            }

            $model->title = $title;
            // $model->replay_category = $replay_category;
            $model->replay_category = $child_category;  // 更新所有回放必须为二级分类下面
            $model->direction = $direction;
            $model->down_url = trim($this->post('down_url', '')) != '' ? trim($this->post('down_url', '')) : $model->down_url;
            $model->play_url = trim($this->post('play_url', '')) != '' ? trim($this->post('play_url', '')) : $model->play_url;
            $model->operator = $this->admin_name;
            $model->update_time = time();

            if (!$model->save()) {
                return static::bulidFail('视频编辑失败');
            }

            return static::bulidSuccess([], '视频编辑成功');
        }

        $parent_id = VideoReplayCategoryModel::where('id', $model->replay_category)->find();
        $parent_category = [];
        if (isset($parent_id->parent_id)) {
            $parent_category = VideoReplayCategoryModel::where('id', $parent_id->parent_id)->find();
        }
        return $this->assign([
            'model' => $model,
            'parent_category' => $parent_category,
            'replay_categorys' => VideoReplayCategoryModel::where('parent_id=0')->column('name', 'id'),
            'child_categorys' => VideoReplayCategoryModel::where('parent_id!=0')->column('name', 'id')
        ])->fetch();
    }

    public function replay_add()
    {
        if ($this->request->isAjax()) {
            if (!$title = trim($this->post('title', ''))) {
                return static::bulidFail('回放标题不能为空');
            }

            if (mb_strlen($title) > 200) {
                return static::bulidFail('回放题长度不能超过200个字符');
            }

            if (!in_array($replay_category = $this->post('replay_category'), VideoReplayCategoryModel::column('id'))) {
                return static::bulidFail('回放类型错误');
            }

            if (!in_array($child_category = $this->post('child_category'), VideoReplayCategoryModel::column('id'))) {
                return static::bulidFail('回放类型错误');
            }

            if (!in_array($direction = $this->post('direction'), ['0', '1'])) {
                return static::bulidFail('横屏竖屏值错误');
            }

            $down_url = trim($this->post('down_url', ''));
            $play_url = trim($this->post('play_url', ''));

            if (!$down_url && !$play_url) {
                return static::bulidFail('视频播放地址不能为空');
            }

            $model = new VideoModel();

            $model->title = $title;
            $model->replay_category = $child_category;
            $model->direction = $direction;
            $model->down_url = trim($this->post('down_url', ''));
            $model->play_url = trim($this->post('play_url', ''));
            $model->type = 5;
            $model->status = 1;
            $model->operator = $this->admin_name;
            $model->update_time = time();
            $model->create_time = time();

            if (!$model->save()) {
                return static::bulidFail('视频添加失败');
            }

            return static::bulidSuccess([], '视频添加成功');
        }
        return $this->assign([
            'replay_categorys' => VideoReplayCategoryModel::where("parent_id=0")->column('name', 'id')
        ])->fetch();
    }

    public function replay_category()
    {
        if ($this->request->isAjax()) {
            $model = VideoReplayCategoryModel::field('*')->where("parent_id=0");
            return json([
                'count' => $model->count('id'),
                'list' => $model->order('sort', 'desc')
                    ->page($this->get('page', 1), $this->get('limit', 20))
                    ->select()->each(function ($query) {
                        $query->create_time = date('Y-m-d H:i:s', $query->create_time);
                    })
                    ->toArray(),
                'code' => 0,
            ]);
        }

        return $this->assign([])->fetch();
    }

    public function replay_child_category_list()
    {
        if ($this->request->isAjax()) {
            $model = VideoReplayCategoryModel::field('*')->where('parent_id!=0');
            $category = intval($this->get('category'));
            if ($category > 0) {
                $model = $model->where("parent_id", $category);
            }
            return json([
                'count' => $model->count('id'),
                'list' => $model->order('sort', 'desc')
                    ->page($this->get('page', 1), $this->get('limit', 20))
                    ->select()->each(function ($query) {
                        $query->create_time = date('Y-m-d H:i:s', $query->create_time);
                    })
                    ->toArray(),
                'code' => 0,
            ]);
        }

        $replay_categorys = VideoReplayCategoryModel::where("parent_id=0")->column('name', 'id');

        return $this->assign(['replay_categorys' => $replay_categorys])->fetch();
    }

    public function repay_child_category()
    {
        $cateogry_id = $this->get('category_id');
        $list = VideoReplayCategoryModel::field('*')->where("parent_id", $cateogry_id)->select();
        return self::bulidSuccess($list);
    }

    public function add_replay_category()
    {
        $hide_parent = $this->get('hide');
        if ($this->request->isAjax()) {
            if (!$name = trim($this->post('name', ''))) {
                return static::bulidFail('分类名称不能为空');
            }

            if (mb_strlen($name) > 30) {
                return static::bulidFail('分类名称长度不能超过30个字符');
            }

            if (!ctype_digit($sort = $this->post('sort'))) {
                return static::bulidFail('排序错误');
            }

            $chick_name =  VideoReplayCategoryModel::where("name", $name)->find();
            if (isset($chick_name['id'])) {
                return static::bulidSuccess([], '分类已存在');
            }

            $model = new VideoReplayCategoryModel();
            $model->parent_id = intval($this->post('parent_id'));
            $model->name = $name;
            $model->sort = $sort;
            $model->create_time = time();
            $model->operator = $this->admin_name;
            $model->status = 0;

            if (!$model->save()) {
                return static::bulidFail('创建失败');
            }

            return static::bulidSuccess([], '创建成功');
        }

        return $this->assign([
            'hide_parent' => $hide_parent,
            'replay_categorys' => VideoReplayCategoryModel::where("parent_id=0")->column('name', 'id')
        ])->fetch();
    }

    public function replay_category_edit()
    {
        if (!ctype_digit($id = $this->get('id'))) {
            return static::bulidFail('参数错误');
        }

        if (!$model = VideoReplayCategoryModel::where('id', $id)->find()) {
            return static::bulidFail('不存在的视频回放分类');
        }

        if ($this->request->isAjax()) {
            if (!$name = trim($this->post('name', ''))) {
                return static::bulidFail('分类名称不能为空');
            }

            if (mb_strlen($name) > 30) {
                return static::bulidFail('分类名称长度不能超过30个字符');
            }

            if (!ctype_digit($sort = $this->post('sort'))) {
                return static::bulidFail('排序错误');
            }

            $parent_id = intval($this->post('parent_id'));
            if ($parent_id > 0) {
                $model->parent_id = $parent_id;
            }
            $model->name = $name;
            $model->sort = $sort;

            if (!$model->save()) {
                return static::bulidFail('编辑失败');
            }

            return static::bulidSuccess([], '编辑成功');
        }

        return $this->assign(['model' => $model, 'replay_categorys' => VideoReplayCategoryModel::where("parent_id=0")->column('name', 'id')])->fetch();
    }

    public function replay_child_category_edit()
    {
        if (!ctype_digit($id = $this->get('id'))) {
            return static::bulidFail('参数错误');
        }

        if (!$model = VideoReplayCategoryModel::where('id', $id)->find()) {
            return static::bulidFail('不存在的视频回放分类');
        }

        if ($this->request->isAjax()) {
            if (!$name = trim($this->post('name', ''))) {
                return static::bulidFail('分类名称不能为空');
            }

            if (mb_strlen($name) > 30) {
                return static::bulidFail('分类名称长度不能超过30个字符');
            }

            if (!ctype_digit($sort = $this->post('sort'))) {
                return static::bulidFail('排序错误');
            }

            $parent_id = intval($this->post('parent_id'));
            if ($parent_id > 0) {
                $model->parent_id = $parent_id;
            }
            $model->name = $name;
            $model->sort = $sort;

            if (!$model->save()) {
                return static::bulidFail('编辑失败');
            }

            return static::bulidSuccess([], '编辑成功');
        }

        return $this->assign(['model' => $model, 'replay_categorys' => VideoReplayCategoryModel::where("parent_id=0")->column('name', 'id')])->fetch();
    }

    public function replay_category_status()
    {
        if (!ctype_digit($id = $this->post('id'))) {
            return static::bulidFail('参数错误');
        }

        if (!ctype_digit($status = $this->post('status'))) {
            return static::bulidFail('参数错误');
        }

        if (!in_array($status, ['0', '1'])) {
            return static::bulidFail('参数错误');
        }

        if (!$model = VideoReplayCategoryModel::where('id', $id)->find()) {
            return static::bulidFail('不存在的视频回放分类');
        }

        $model->status = $status;

        if (!$model->save()) {
            return static::bulidFail('操作失败');
        }

        return static::bulidSuccess([], '操作成功');
    }
}
